#include "ycompress.h"
#include "mylogger.h"
#include <QDebug>

using namespace ns_yht;

YCompress::YCompress() {}

QStringList YCompress::extractDirWithRename(QString fileCompressed, QTextCodec *fileNameCodec, QString dir)
{
    QuaZip zip(fileCompressed);
    if (fileNameCodec)
        zip.setFileNameCodec(fileNameCodec);
    return extractDirWithRename(zip, dir);
}

QStringList YCompress::extractDirWithRename(QuaZip &zip, const QString &dir)
{
    if (!zip.open(QuaZip::mdUnzip))
    {
        if (GLOG)
            GLOG->info("extract false ============zip.open(QuaZip::mdUnzip)------{}", dir.toStdString());
        return QStringList();
    }
    QString cleanDir = QDir::cleanPath(dir);
    QDir directory(cleanDir);
    QString absCleanDir = directory.absolutePath();
    if (!absCleanDir.endsWith('/')) // It only ends with / if it's the FS root.
        absCleanDir += '/';
    QStringList extracted;
    if (!zip.goToFirstFile())
    {
        return QStringList();
    }
    do
    {
        QString name = zip.getCurrentFileName();
        QString absFilePath = directory.absoluteFilePath(name);
        QString absCleanPath = QDir::cleanPath(absFilePath);
        if (!absCleanPath.startsWith(absCleanDir))
            continue;

        if (GLOG)
            GLOG->info("extract ===================== {} ", name.toStdString());

        bool oldExist = !name.endsWith('/') && QFile::exists(absCleanPath);
        // if(GLOG)GLOG->info(oldExist?"old file exists---------------":"new file----------");
        QString oldFile;
        if (oldExist)
        {
            oldFile = absCleanPath + ".old";
            QFile::rename(absCleanPath, oldFile);
        }

        if (!extractFile(&zip, QLatin1String(""), absFilePath))
        {
            if (GLOG)
                GLOG->critical("extract false!!! ============ {}", absFilePath.toStdString());
            removeFile(extracted);
            return QStringList();
        }
        // 尝试删除原来的文件，不管是否成功都继续
        if (oldExist && !removeFile({oldFile}) && GLOG)
            GLOG->info(" {}  is occupied!.......", absCleanPath.toStdString());
        extracted.append(absFilePath);
    } while (zip.goToNextFile());

    // Chiudo il file zip
    zip.close();
    if (zip.getZipError() != 0)
    {
        if (GLOG)
            GLOG->critical("extract false!!!  ZIP Error: {}", zip.getZipError());
        removeFile(extracted);
        return QStringList();
    }
    if (GLOG)
        GLOG->info("extract succeed!!!");
    return extracted;
}
